/** ***********************************************
 * CodeGen
 *
 * @author  Jonnie Spratley
 * @date 3/05/2009
 * @licence MCIYC
 * @website http://jonniespratley.com/code
 * @contact jonniespratley@gmail.com
 *********************************************** */
package com.jonniespratley.codegen.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.jonniespratley.codegen.business.CodeGenDelegate;
	import com.jonniespratley.codegen.events.GenerateConfigEvent;
	import com.jonniespratley.codegen.model.ModelLocator;
	import com.jonniespratley.codegen.vo.*;

	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	/**
	 * For every feature or use case in your application, a corresponding custom command
	 * and event must be created. Each command contains an execute() method that is run
	 * by the framework when the user action has been executed.
	 * These classes are occasionally referred to as worker classes because they carry
	 * out the work for an application.
	 *
	 */
	public class GenerateConfigCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			var evt:GenerateConfigEvent = event as GenerateConfigEvent;
			var delegate:CodeGenDelegate = new CodeGenDelegate( this );
				delegate.generateConfig( evt.aConfig );

		}

		public function result( data:Object ) : void
		{
			var resultObj:ResultEvent = data as ResultEvent;
			model.configLocation = String( resultObj.result );
			model.currentConfig = resultObj.token.config;

			/*
			if ( resultObj.result is String )
			{
				var rawData:String = String( resultObj.result );
				var jsonArray:Array = ( JSON.decode( rawData ) as Array );
				var tempAC:ArrayCollection = new ArrayCollection();

				for ( var s:String in jsonArray )
				{
					tempAC.addItem( new ConfigVO( jsonArray[s] ) );
				}
				model.configCollection = tempAC;
				model.currentConfig = new ConfigVO( jsonArray[ s ] );

				var configTree:Array = [ new ConfigVO( jsonArray[ s ] ) ];

				model.configTree = new ArrayCollection( configTree );
			}
			*/
			model.configLocation = String( resultObj.result ).replace( /[\\]*[\\"]/g, '' );

		}

		public function fault( fault:Object ):void
		{
			var faultEvt:FaultEvent = fault as FaultEvent;

			trace(faultEvt.fault.faultString);
		}
	}
}
